package com.lc.tgxm.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.lc.tgxm.BaseApplication;
import com.lc.tgxm.R;
import com.lc.tgxm.widget.ViewTitle;
import com.zcx.helper.activity.AppPictureActivity;
import com.zcx.helper.scale.ScaleScreenHelperFactory;
import com.zcx.helper.util.UtilToast;

import java.util.ArrayList;

/**
 * BaseActivity Activity基类
 * Created by Lei on 2017/01/18.
 */
public class BasePicActivity extends AppPictureActivity {
    protected String TAG = getClass().getSimpleName();
    protected ViewTitle viewTitle;

    /**
     * 初始化布局，并且设置标题
     *
     * @param layoutResId Resource ID to be inflated.
     * @param resId       标题文字资源 (e.g., R.string.title)
     */
    protected void initContenView(int layoutResId, int resId) {
        setContentView(layoutResId);
        setTitleName(resId);
    }

    /**
     * 初始化布局(标题栏左侧有返回键，点击关闭)，并且设置标题
     *
     * @param layoutResId Resource ID to be inflated.
     * @param resId       标题文字资源 (e.g., R.string.title)
     */
    protected void initContenViewAndBack(int layoutResId, int resId) {
        setContentView(layoutResId);
        initTitlebarBack(resId);
        // 动态权限申请
        applyPermissions(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA);
    }

    /**
     * 设置标题，标题栏左侧有返回键，点击关闭
     *
     * @param resid 标题文字(e.g., R.string.title)
     */
    protected void initTitlebarBack(int resid) {
        viewTitle = (ViewTitle) findViewById(R.id.titlebar);
        viewTitle.setTitleName(resid);
        View ivLeft = viewTitle.activateView(ViewTitle.TitleType.BACK);
        ivLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    /**
     * 设置标题
     *
     * @param resid 标题文字(e.g., R.string.title)
     */
    protected void setTitleName(int resid) {
        viewTitle = (ViewTitle) findViewById(R.id.titlebar);
        viewTitle.setTitleName(resid);
    }

    /**
     * 设置标题
     *
     * @param name 标题文字(String类型)
     */
    protected void setTitleName(String name) {
        viewTitle = (ViewTitle) findViewById(R.id.titlebar);
        viewTitle.setTitleName(name);
    }

    /**
     * 动态权限申请 地图定位相关权限
     */
    protected void permissionLocationMap() {
        String[] permissions = new String[]{
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        applyPermissions(permissions);
    }

    /**
     * 按钮点击事件 在布局文件里设置 android:onClick="onButtonClick"
     *
     * @param view 产生点击事件的View
     */
    public void onButtonClick(View view) {
    }

    /**
     * 初始化PopupWindow
     *
     * @param resource ID for an XML layout resource to load (e.g., R.layout.main_page)
     * @return PopupWindow
     */
    protected PopupWindow initPopWindow(int resource) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View pView = inflater.inflate(resource, null);
        ScaleScreenHelperFactory.getInstance().loadViewGroup((ViewGroup) pView);

        PopupWindow pw = new PopupWindow(pView);
        pw.setFocusable(true);
        pw.setOutsideTouchable(true);
        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        pw.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                blurredBackground(1.0f);
            }
        });
        return pw;
    }

    /**
     * 初始化 底部弹出的宽高
     *
     * @param resource ID for an XML layout resource to load (e.g., R.layout.main_page)
     * @return PopupWindow
     */
    protected PopupWindow initPopWindowFromBototm(int resource) {
        PopupWindow pw = initPopWindow(resource);
        pw.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pw.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        return pw;
    }

    /**
     * 从屏幕底部弹出PopupWindow
     */
    protected void showPwFromBottom(PopupWindow pw) {
        if (pw == null)
            return;
        pw.setAnimationStyle(R.style.PopupAnimation);
        pw.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        // 背景变暗
        blurredBackground(0.7f);
    }

    /**
     * 背景变暗
     *
     * @param alpha 0.7f变暗;1.0f回复原状
     */
    protected void blurredBackground(float alpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = alpha;
        getWindow().setAttributes(lp);
    }

    /**
     * 获取屏幕宽高
     *
     * @return int[0] width(宽度);int[1] height(高度)
     */
    protected int[] getDisplayWidthHeight() {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        return new int[]{displaymetrics.widthPixels, displaymetrics.heightPixels};
    }

    @Override
    protected void resultPhotoPath(ImageView imageView, String s) {

    }

    /**
     * 动态申请权限
     */
    protected void applyPermissions(String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> needPermissions = new ArrayList<>();
            for (String aPermission : permissions) {
                if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, aPermission)) {
                    needPermissions.add(aPermission);
                }
            }
            if (needPermissions.isEmpty()) {
                onPermissionSuccess();
            } else {
                final String[] array = needPermissions.toArray(new String[needPermissions.size()]);
                ActivityCompat.requestPermissions(this, array, 1);
            }
        } else {
            onPermissionSuccess();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean allGranted = true;
        if (grantResults.length > 0) {
            for (int result : grantResults) {
                if (result == PackageManager.PERMISSION_DENIED) {
                    allGranted = false;
                    break;
                }
            }
            if (allGranted) {
                onPermissionSuccess();
            } else {
                onPermissionDenied();
            }
        } else {
            onPermissionDenied();
        }
    }

    /**
     * 权限成功后回调方法
     */
    protected void onPermissionSuccess() {
    }

    /**
     * 权限失败后回调方法
     */
    protected void onPermissionDenied() {
        UtilToast.show(R.string.to_permissondenied);
    }

    protected boolean checkEmpty(String... strs) {
        for (String name : strs) {
            if (TextUtils.isEmpty(name)) {
                return true;
            }
        }

        return false;
    }

    protected String getUserId() {
        return BaseApplication.basePreferences.getUserId();
    }
}